package xyz.liut.ee.web

import jakarta.servlet.ServletContextEvent
import jakarta.servlet.ServletContextListener
import jakarta.servlet.annotation.WebListener
import xyz.liut.logcat.L
import xyz.liut.logcat.handler.FileHandler
import xyz.liut.logcat.handler.StdHandler
import java.text.SimpleDateFormat
import java.util.*

private const val TAG = "WebContextListener"

/**
 * create by liut on 19-1-14
 */
@Suppress("unused")
@WebListener(value = "初始化")
class WebContextListener : ServletContextListener {

    init {
        val format = SimpleDateFormat("HH:mm:ss", Locale.CHINA)
        val stdHandler = StdHandler()
        L.getDefault()
            .addHandler { level, tag, msg ->
                stdHandler.log(level, "${format.format(Date())} $tag", msg)
            }
            .addHandler(FileHandler("./files/logcat.log"))
    }

    override fun contextInitialized(sce: ServletContextEvent) {
        L.d(TAG, "server started: $sce")

//        // 读取配置文件
//        try {
//            Config.init()
//        } catch (e: IOException) {
//            L.e(TAG, "读取./properties出错: " + e.message)
//        }

//        // 初始化数据库
//        try {
//            new DatabaseInit().init();
//        } catch (SQLException e) {
//            L.e(TAG, "初始化数据库失败", e);
//            System.exit(-1);
//        }
    }

    override fun contextDestroyed(sce: ServletContextEvent) {
        L.d(TAG, "server stopped: $sce")
    }

}
